package com.cyy.util

import javafx.embed.swing.SwingFXUtils
import javafx.scene.image.Image
import org.apache.commons.imaging.ImageFormats
import org.apache.commons.imaging.Imaging
import javax.imageio.ImageIO
import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.io.File
import java.io.IOException

object ImageUtil {
    /**
     * 获取图片BufferedImage
     * @param path 图片路径
     */
    fun getBufferedImage(path: String): BufferedImage? {
        return getBufferedImage(File(path))
    }

    fun getBufferedImage(file: File): BufferedImage? {
        var bufferedImage: BufferedImage? = null
        try {
            bufferedImage = Imaging.getBufferedImage(file)
        } catch (e: Exception) {
            try {
                bufferedImage = ImageIO.read(file)
            } catch (e1: IOException) {
                e1.printStackTrace()
            }

        }

        return bufferedImage
    }

    /**
     * 获取javafx图片
     * @param path 图片路径
     */
    fun getFXImage(path: String): Image? {
        return getFXImage(File(path))
    }

    fun getFXImage(file: File): Image? {
        var image: Image? = null
        try {
            image = SwingFXUtils.toFXImage(Imaging.getBufferedImage(file), null)
        } catch (e: Exception) {
            image = Image("file:" + file.absolutePath)
        }

        return image
    }

    fun getFXImage(bytes: ByteArray): Image? {
        var image: Image? = null
        try {
            image = SwingFXUtils.toFXImage(Imaging.getBufferedImage(bytes), null)
        } catch (e: Exception) {
            image = Image(ByteArrayInputStream(bytes))
        }

        return image
    }


    /**
     * 保存图片
     * @param image
     * @param file
     */
    @Throws(Exception::class)
    fun writeImage(image: Image, file: File) {
        writeImage(SwingFXUtils.fromFXImage(image, null), file)
    }

    @Throws(Exception::class)
    fun writeImage(bufferedImage: BufferedImage, file: File) {
        try {
            Imaging.writeImage(bufferedImage, file, ImageFormats.valueOf(FileUtil.getFileSuffixName(file)!!.toUpperCase()), null)
        } catch (e: Exception) {
            e.printStackTrace()
            ImageIO.write(bufferedImage, FileUtil.getFileSuffixName(file), file)
        }

    }
}